package com.bytecollege.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName: ImageUploadUtil
 * @Description: 保存文件到 /upload/
 * @Author: UnknownDotEdge
 * @Date: 2022/10/19 11:12
 */
public class FileUploadUtil {
    public static Map<String, Object> save(MultipartFile file) {
        String path = System.getProperty("user.dir") + "/upload/";
        //按照月份进行分类：
        Calendar instance = Calendar.getInstance();
        String month = (instance.get(Calendar.MONTH) + 1) + "";
        path = path + month;
        Map<String, Object> res = new HashMap<>();

        File realPath = new File(path);
        if (!realPath.exists()) {
            System.out.println(realPath.mkdirs());
        }

        //上传文件地址
        System.out.println("上传文件保存地址：" + realPath);
        String name = file.getOriginalFilename();
        String fileSuffix = name.substring(name.lastIndexOf("."));
        //解决文件名字问题：使用uuid;
        String filename = "file-" + UUID.randomUUID().toString().replaceAll("-", "");
//        通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        try {
            file.transferTo(new File(realPath + "/" + filename + fileSuffix));
            res.put("url", "/upload/" + month + "/" + filename + fileSuffix);
            res.put("success", true);
            res.put("message", "upload success!");
        } catch (IOException e) {
            e.printStackTrace();
            res.put("success", false);
            res.put("message", "upload fail!");
            e.printStackTrace();
        }
        return res;
    }
}
